<template>
  <div class="wrap">
    <el-card class="header-card">
      <div class="item">
        <p class="font-bold">{{ $t('table.贴标单号') }}：{{ data.labelNo }}</p>
        <p class="font-bold" v-if="data.shipment">{{ $t('table.shipmentNumber') }}：{{ data.shipment.shipmentNo }}</p>
        <p class="font-bold" v-if="data.middle">{{ $t('table.送仓单号') }}：{{ data.middle.workNo }}</p>
        <p class="font-bold" v-if="data.transfer">{{ $t('table.调货单号') }}：{{ data.transfer.workNo }}</p>
        <p class="font-bold">{{ $t('table.贴标类型') }}：{{ getLabelTypeStr(data.type) }}</p>
        <p class="font-bold">{{ $t('table.贴标状态') }}：{{ getLabelStatusStr(data.status) }}</p>
        <p>{{ $t('table.createTime2') }}：{{ data.createTime }}</p>
        <p>
          {{ $t('table.预计贴标SKU种数') }}: {{ data.exSkuNum }}
          <span class="mgl20">{{ $t('table.预计贴标商品总数量') }}：{{ data.exGoodsNum }}</span>
        </p>
        <p v-if="data.status === 2">
          {{ $t('table.实际贴标SKU种数') }}: <span :class="{'font-red': data.rlSkuNum !== data.exSkuNum}">{{ data.rlSkuNum }}</span>
          <span class="mgl20">{{ $t('table.实际贴标商品总数量') }}：<span :class="{'font-red': data.exGoodsNum !== data.rlGoodsNum}">{{ data.rlGoodsNum }}</span></span>
        </p>
        <p>
          {{ $t('table.贴SKU标单价（元）') }}: {{ data.labelFee }}
        </p>
        <p v-if="data.status !== 2">
          <span>{{ $t('table.预计贴SKU标费用（元）') }}：{{ data.exTotalFee }}</span>
        </p>
        <p v-else>
          <span>{{ $t('table.实际贴SKU标费用（元）') }}：{{ data.rlTotalFee }}</span>
        </p>
      </div>
      <div class="button">
        <div v-if="data.shipment">
          <el-button type="primary" @click="jumpShipmentInfo(data.shipment.id, true)">{{ $t('shipment.货件单') }}</el-button>
        </div>
        <div v-if="data.transfer">
          <el-button type="primary" @click="jumpTransferInfo(data.transfer.id, true)">{{ $t('transfer.调货工单') }}</el-button>
        </div>
        <div v-if="data.middle">
          <el-button type="primary" @click="jumpMiddleInfo(data.middle.id, true)">{{ $t('middle.送仓工单') }}</el-button>
        </div>
      </div>
    </el-card>



    <div>
      <h4>{{ $t('labelOrder.贴标商品详细情况') }}：</h4>
      <template v-if="data.type === 1">
        <label-order-info-table1 :data="data" :table-data="goodsData"></label-order-info-table1>
      </template>

      <template v-if="data.type === 2">
        <el-table
          :data="goodsData"
          :border="true"
          :span-method="objectSpanMethod3"
        >
          <el-table-column
            prop="image"
            :label="$t('table.productCover')"
            align="center"
            width="120"
          >
            <template slot-scope="{row}">
              <div class="img-box img-one">
                <img :src="row.image" alt="">
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="title"
            :label="$t('table.title')"
            align="left"
            show-overflow-tooltip
            min-width="250"
          >
            <template slot-scope="{row}">
              <div>
                <div class="goods-title hidden-1">{{row.title}}</div>
                <div class="goods-attr hidden-1">
                  <span
                    v-for="attr in row.attributes"
                    :key="attr.name"
                    class="attr"
                  >
                    {{attr.name}} : {{attr.value}}
                    <span class="attr-link"> | </span>
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('table.本次贴标的Listing ID与SKU')"
            align="center"
            min-width="150"
            prop="toGoodsId"
          >
            <template v-slot="{row}">
              {{row.toGoodsId}} {{row.toSku ? `(${row.toSku})` : ''}}
            </template>
          </el-table-column>
          <m-l-code-column lable='新产品标' prop="toInventoryId"></m-l-code-column>
          <el-table-column
            label="旧产品标"
            align="center"
            min-width="150"
            prop="fromGoodsId"
          >
            <template v-slot="{row}">
              <template v-if="row.fromGoodsIsTB">
                {{$t('shipment.Not labeled')}}
              </template>
              <template v-else-if="row.fromGoodsIsSystem">
                <!-- {{$t('shipment.System label')}} -->
                 ({{row.fromSku}})
              </template>
              <template v-else>
                {{row.fromGoodsId}} {{row.fromSku ? `(${row.fromSku})` : ''}}
              </template>
            </template>
          </el-table-column>
        <!--  <m-l-code-column prop="fromInventoryId" label="调出MLCode"></m-l-code-column> -->
         <!-- <el-table-column
            :label="$t('table.从一件代发库存调出')"
            align="center"
            width="150"
            prop="exOneStock"
          >
            <template v-slot="{row}">
              <template v-if="row.stockBoxInfo.length === 0"> - </template>
              <template v-else>
                <div
                  v-for="(item,index) in row.stockBoxInfo"
                  :key="index"
                >
                  {{$t('table.num/箱',{num: item.goodsNumInBox})}} × {{item.editNum}}
                </div>
              </template>
            </template>
          </el-table-column> -->
          <el-table-column
            :label="$t('table.从中转送仓库存调出')"
            align="center"
            width="150"
            prop="exMiddleStock"
          >
            <template v-slot="{row}" >

              <template v-if="row.middleBoxInfo.length > 0">
                <div
                  v-for="(item,index) in row.middleBoxInfo"
                  :key="index"
                >
                  {{$t('table.num/箱',{num: item.goodsNumInBox})}} × {{item.editNum}}
                </div>
              </template>
              <template v-else-if="row.stockBoxInfo.length > 0">
                <div
                  v-for="(item,index) in row.stockBoxInfo"
                  :key="index"
                >
                  {{$t('table.num/箱',{num: item.goodsNumInBox})}} × {{item.editNum}}
                </div>
              </template>
              <template v-else> - </template>
            </template>
          </el-table-column>

         <!-- <template v-if="data.status === 2">
            <el-table-column
              :label="$t('table.从一件代发实际贴标')"
              align="center"
              width="150"
              prop="rlOneStock"
            >
              <template v-slot="{row}">
                <span :class="[row.rlOneStock !== row.exOneStock ? 'font-red' : '']">{{row.rlOneStock}}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.从中转送仓实际贴标')"
              align="center"
              width="150"
              prop="rlMiddleStock"
            >
              <template v-slot="{row}">
                <span :class="[row.rlMiddleStock !== row.exMiddleStock ? 'font-red' : '']">{{row.rlMiddleStock}}</span>
              </template>
            </el-table-column>
          </template> -->

          <el-table-column
            :label="$t('table.预计贴标商品总数量')"
            width="200"
            prop="totalExGoodsNum"
            align="center"
          >
          </el-table-column>
          <template v-if="data.status === 2">
            <el-table-column
              :label="$t('table.实际贴标商品总数量')"
              width="200"
              prop="totalRlGoodsNum"
              align="center"
            >
              <template v-slot="{row}">
                <span :class="[row.totalRlGoodsNum !== row.totalRlGoodsNum ? 'font-red' : '']">{{row.totalRlGoodsNum}}</span>
              </template>
            </el-table-column>
          </template>

          <el-table-column
            :label="$t('table.官方SKU标')"
            width="150"
            prop="labelPdf"
          >
            <template slot-scope="{row}">
              <upload-goods-label
                :id="row.toSuitListId"
                :file="row.labelPdf"
                :data-obj="row"
              ></upload-goods-label>
            </template>
          </el-table-column>

        </el-table>
      </template>

      <template v-if="data.type === 3">
        <el-table
          :data="goodsData"
          :border="true"
          class="goods-table"
          :span-method="objectSpanMethod3"
        >
          <el-table-column
            prop="image"
            :label="$t('table.productCover')"
            align="center"
            width="120"
          >
            <template slot-scope="{row}">
              <div class="img-box img-one">
                <img :src="row.image" alt="">
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="title"
            :label="$t('table.title')"
            align="left"
            show-overflow-tooltip
            min-width="250"
          >
            <template slot-scope="{row}">
              <div>
                <div class="goods-title hidden-1">{{row.title}}</div>
                <div class="goods-attr hidden-1">
                  <span
                    v-for="attr in row.attributes"
                    :key="attr.name"
                    class="attr"
                  >
                    {{attr.name}} : {{attr.value}}
                    <span class="attr-link"> | </span>
                  </span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('table.本次贴标的Listing ID与SKU')"
            align="center"
            min-width="150"
            prop="toGoodsId"
          >
            <template v-slot="{row}">
              {{row.toGoodsId}} {{row.toSku ? `(${row.toSku})` : ''}}
            </template>
          </el-table-column>
          <m-l-code-column label="新产品标" prop="toInventoryId"></m-l-code-column>
          <el-table-column
            label="旧产品标"
            align="center"
            min-width="150"
            prop="fromGoodsId"
          >
            <template v-slot="{row}">
              <template v-if="row.fromGoodsIsTB">
                {{$t('shipment.Not labeled')}}
              </template>
              <template v-else>
                <!-- {{row.fromGoodsId}} -->
                {{row.fromSku ? `${row.fromSku}` : ''}}
              </template>
            </template>
          </el-table-column>
         <!-- <m-l-code-column prop="fromInventoryId" label="调出MLCode"></m-l-code-column> -->
          <el-table-column
            :label="$t('table.从中转送仓库存调出')"
            align="center"
            width="150"
            prop="exGoodsNum"
          >
            <template v-slot="{row}">
              <template v-if="row.middleBoxInfo.length === 0"> - </template>
              <template v-else>
                <div
                  v-for="(item,index) in row.middleBoxInfo"
                  :key="index"
                >
                  {{$t('table.num/箱',{num: item.goodsNumInBox})}} × {{item.editNum}}
                </div>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('table.预计贴标商品总数量')"
            width="200"
            prop="totalExGoodsNum"
            align="center"
          >
          </el-table-column>
          <template v-if="data.status === 2">
            <el-table-column
              :label="$t('table.实际贴标商品总数量')"
              width="200"
              prop="totalRlGoodsNum"
              align="center"
            >
              <template v-slot="{row}">
                <span :class="[row.totalRlGoodsNum !== row.totalExGoodsNum ? 'font-red' : '']">{{row.totalRlGoodsNum}}</span>
              </template>
            </el-table-column>
          </template>
          <el-table-column
            :label="$t('table.官方SKU标')"
            width="150"
            prop="labelPdf"

          >
            <template slot-scope="{row}">
                <upload-goods-label
                  :id="row.toSuitListId"
                  :file="row.labelPdf"
                  :data-obj="row"
                ></upload-goods-label>
            </template>
          </el-table-column>

        </el-table>
      </template>

    </div>

    <div class="remark" v-if="data.remark">
      <h4>{{$t('shipment.step4Text10')}}：</h4>
      <el-input type="textarea" style="width: 1500px"  v-model="data.remark" autosize></el-input>
    </div>


    <div class="font-grey mgt10" style="font-size: 13px">

      <template v-if="data.type === 1">
        <div>请通过右侧「选择产品标」按钮确认每箱未贴标商品贴什么产品标</div>
        <div>官方产品标需要您上传后才可选择（若之前没有上传）</div>
      </template>
      <template v-else>
        <div>{{$t('labelOrder.系统标的SKU仅需确认贴标的数量')}}</div>
        <div>{{$t('labelOrder.官方仓的SKU需要确认数量以及上传官方标（若之前没有上传)')}}</div>
      </template>

    </div>

    <div class="mgt20">
      <el-button @click="jumpPage('labelList')">{{$t('common.back')}}</el-button>
      <el-button type="primary" @click="confirmData" v-if="data.status === 0">{{ $t('common.confirm') }}</el-button>

      <!-- 只有入库贴标可以修改贴标 -->
      <el-button type="primary" @click="editData" v-if="data.status === 1 && data.type === 1">修改</el-button>
    </div>
  </div>
</template>

<script>
import UploadGoodsLabel from "@/views/stock/components/UploadGoodsLabel";
import {confirmLabelOrder, editLabelOrder, getLabelOrderInfo} from "@/api/labelOrder";
import {deepCopy} from "@/utils";
import {jumpMiddleInfo, jumpPage, jumpShipmentInfo, jumpTransferInfo} from "@/utils/jumpView";
import {getLabelStatusStr, getLabelTypeStr} from "@/utils/labelOrder";
import MLCodeColumn from "@/views/stock/components/MLCodeColumn.vue";
import LabelOrderInfoTable1 from "@/views/labelOrder/components/LabelOrderInfoTable1.vue";

export default {
  name: "labelOrderInfo",
  components: {LabelOrderInfoTable1, MLCodeColumn, UploadGoodsLabel},
  data(){
    return {
      id: 0,
      loading: false,
      data: {},
      goodsData: [],
      btnLoading: false,
    }
  },
  created() {
    this.id = this.$route.query.id
    this.getData()
  },
  methods:{
    getLabelStatusStr,
    getLabelTypeStr,
    jumpMiddleInfo,
    jumpTransferInfo,
    jumpPage,
    jumpShipmentInfo,
    getData(){
      this.loading = true
      getLabelOrderInfo(this.id)
        .then(res=>{
          this.loading = false
          if(res.error === 0){
            this.data = deepCopy(res.data)
            this.goodsData = []
            res.info.goodsData.forEach(item=>{
              this.goodsData.push(item)
            })
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    // 确认数据
    confirmData(){
      if(!this.validData()){
        return;
      }

      const postData = {
        id: this.data.id,
        goodsList: this.goodsData
      }

      this.btnLoading = true
      confirmLabelOrder(postData)
        .then(res=>{
          this.btnLoading = false
          if(res.error === 0){
            this.getData()
            this.$successMessage(res.message)
            const planId = res.data.planId
            if(planId){
              // 确认完之后 跳转回发货计划
              this.$router.push({
                name: 'shippingPlanInfo',
                query: {
                  id: planId
                }
              })
            }
          }else{
            this.$errorMessage(res.message)
          }
        })
        .catch(res=>{
          this.btnLoading = false
        })


    },
    // 修改数据
    editData(){
      if(!this.validData()){
        return;
      }
      const postData = {
        id: this.data.id,
        goodsList: this.goodsData
      }
      this.btnLoading = true
      editLabelOrder(postData)
        .then(res=>{
          this.btnLoading = false
          if(res.error === 0){
            this.getData()
            this.$successMessage(res.message)
          }else{
            this.$errorMessage(res.message)
          }
        })
    },
    // 校验提交的数据
    validData(){
      // 入库贴标
      if(this.data.type === 1){
        return this.goodsData.every(item=>{
          if(!item.toSuitId){
            this.$errorMessage(item.boxId + '请选择产品标')
          }
          return item.toSuitId
        })
      }

      // 校验是否上传了sku标
      if(!this.goodsData.filter(item => (item.editExGoodsNum > 0 || item.editExBoxNum > 0) && item.isGoods).every(item => item.labelPdf !== '')){
        this.$errorMessage(this.$t('labelOrder.请上传官方SKU标'))
        return false;
      }

      // 校验贴标数量是否相等
      if(this.data.type === 1){
        const goodsDataNum = {}
        this.goodsData.forEach(item=>{
          if(!goodsDataNum[item.fromSuitId]){
            goodsDataNum[item.fromSuitId] = {
              totalNum: item.totalExGoodsNum,
              currentNum: 0
            }
          }
          if(item.editExGoodsNum === undefined){
            item.editExGoodsNum = 0
          }
          if(item.editExBoxNum === undefined){
            item.editExBoxNum = 0;
          }
          goodsDataNum[item.fromSuitId].currentNum += (item.editExGoodsNum + item.editExBoxNum * item.goodsNumInBox)
        })
        for (const suitId in goodsDataNum) {
          if(goodsDataNum[suitId].totalNum !== goodsDataNum[suitId].currentNum){
            this.$errorMessage(this.$t('labelOrder.“预计贴标商品总数”必须等于当前商品“未贴标商品总数”'));
            return false;
          }
        }
      }

      return true;
    },
    goShipment(){

    },
    objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.mergeCell1()
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    objectSpanMethod3({ row, column, rowIndex, columnIndex }){
      const mergeCell = this.mergeCell3()
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    mergeCell1(){
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'image',
        'title',
        'totalExGoodsNum',
        'totalRlGoodsNum',
        'goodsNumBox',
        'mixinGoodsNum',
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      this.goodsData.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并
        if(item.fromSuitId && item.fromSuitId === this.goodsData[index - 1].fromSuitId){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
    mergeCell3(){
      const mergeField = 'toSuitListId'
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'image',
        'title',
        'toGoodsId',
        'totalExGoodsNum',
        'totalRlGoodsNum',
        'labelPdf',
        'toInventoryId',
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      this.goodsData.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并
        if(item[mergeField] && item[mergeField] === this.goodsData[index - 1][mergeField]){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
    // 计算商品总数量
    calTotalExGoodsNum(row){
      return this.goodsData.filter(item => item.toSuitId === row.toSuitId)
        .reduce((sum,cur) => sum + cur.goodsNumInBox * cur.editExBoxNum + cur.editExGoodsNum , 0)
    },
    calTotalRlGoodsNum(row){
      return this.goodsData.filter(item => item.toSuitId === row.toSuitId)
        .reduce((sum,cur) => sum + cur.goodsNumInBox * cur.rlBoxNum + cur.rlGoodsNum , 0)
    }
  }
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header{
    //display: flex;
    //justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }
  .header-card{
    font-size: 14px;
    background-color: rgba(242, 242, 242, 1);
    p{
      margin: 10px 0;
      padding: 0;
    }
    .font-bold{
      font-weight: bold;
    }
    .true-number{
      color: #FF0000;
      font-weight: 600;
    }
  }
}
.goods-table{
  .goods-title{
    font-size: 14px;
  }
  .goods-attr{
    font-size: 13px;
    color: #7F7F7F;
  }
}
.table-tips{

}

.header-card{
  position: relative;
  .button{
    position: absolute;
    display: flex;
    flex-direction: column;
    right: 20px;
    top: 30px;
  }
}
</style>
